//封装axios
import axios from "axios"
import globalConfig from "./white.config"
import router from '../routers/router'
import LocalStorageUtil from "../utils/LocalStorageUtil";

// Set config defaults when creating the instance
const shaxios = axios.create({
    //正式开发
    // baseURL: import.meta.env.VITE_APP_SERVER,
    //默认根域名 跨域用
    baseURL: '/',
    withCredentials: true
});

// Alter defaults after instance has been created

//1、通用默认配置

//配置默认token  ---headers 配置请求也会导致跨域问题，需要配置Access-Control-Allow-Headers: test,test1,Content-Type
//shaxios.defaults.headers.common['Authorization'] = "AUTH_TOKEN";
// 内容类型
shaxios.defaults.headers.post['Content-Type'] = 'application/json';
//超时时间
shaxios.defaults.timeout = 25000;

//2、拦截器配置
shaxios.interceptors.request.use(function (config) {
        /*...token等配置*/
        let whiteList = globalConfig.whiteListApi;
        let url = config.url ? config.url : '';
        const token:string = LocalStorageUtil.get("token");
        const id = LocalStorageUtil.get("id");
        if(whiteList.indexOf(url) === -1 && token){ //不存在白名单中且token不为空
            // config.headers['auth-token'] = token //设置token
            config.headers['Token'] = token //设置token
            config.headers['Storeid'] = id //设置token
        }
        return config;
    },error=>{
        return Promise.reject(error) //错误处理
    }
)

shaxios.interceptors.response.use((res)=> {
    /*...响应相关统一处理*/
    if(res.data.code === 0 && res.data.data === 300) {
        // 跳转登陆
        router.push("/login");
        return;
    }
    return res
},error=>{
    const status = error.response?.status
    const message = "未知错误"
    if(status === 401){
        console.log("请先登录！")
        // 清空session和local
        LocalStorageUtil.clearExcept(["username","password"]);
        sessionStorage.clear();
        router.push("/login")
    }
    if(status === 403){
        console.log("无权限访问！")
        return Promise.reject(new Error("无权限访问！"))//错误处理
    }
    if(status && status !== 200){
        return Promise.reject(new Error("错误："+status+" "+message))//错误处理
    }
    return Promise.reject(error)//错误处理
})

export default shaxios
